<?php

namespace App\Console\Commands\WorkOrder;

use App\Models\WorkOrder\WorkOrderApplyContentModel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class WorkOrderApplyContentUpdateNull extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'workOrder:updateContentNull';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '刷新工单详情中处理人/供应商为空的情况';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        WorkOrderApplyContentModel::query()
            ->whereRaw(DB::raw("JSON_CONTAINS(content, JSON_OBJECT('handle', null))"))
            ->orWhereRaw(DB::raw("JSON_CONTAINS(content, JSON_OBJECT('handle', 0))"))
            ->orWhereRaw(DB::raw("JSON_CONTAINS(content, JSON_OBJECT('chooseFactory', null))"))
            ->select(['id', 'workOrderNo', 'content'])
            ->get()
            ->map(
                function ($workOrderApplyContentModel) {
                    $content = json_decode($workOrderApplyContentModel->content ?? '', true);
                    if ($content) {
                        $newContent = [];
                        foreach ($content as $k => $v) {
                            if ($k == 'handle' || $k == 'chooseFactory') {
                                $v = array_values(array_filter($v));// 过滤空值
                            }
                            $newContent[$k] = $v;
                        }

                        WorkOrderApplyContentModel::query()
                            ->where('id', $workOrderApplyContentModel->id)
                            ->update(['content' => json_encode($newContent, JSON_UNESCAPED_UNICODE)]);

                        dump('workOrderNo... ' . $workOrderApplyContentModel->workOrderNo);
                    }
                }
            );
    }
}
